<template>
  <div class="wang-editor-container">
    <Toolbar
      class="tool-bar"
      :defaultConfig="toolbarConfig"
      :mode="mode"
      :editor="editorRef"
      v-if="editorRef"
    />
    <Editor
      style="height: 400px; overflow-y: hidden"
      v-model="valueHtml"
      :defaultConfig="editorConfig"
      :mode="mode"
      @onCreated="onEditorCreated"
      @onChange="onChangeEditor"
    />
  </div>
</template>

<script lang="ts" setup>
/**
 * 导入模块
 */
import AliyunOss from '@/plugins/oss/index';
import { Editor, Toolbar } from '@wangeditor-next/editor-for-vue';

/**
 * 导入类型声明
 */
import type { IDomEditor, IEditorConfig } from '@wangeditor-next/editor';

/**
 * props的interface
 */
interface PropType {
  modelValue: string;
}

/**
 * 定义props
 */
const props = defineProps<PropType>();

/**
 * 定义emits的类型声明
 */
interface EmitType {
  (e: 'update:modelValue', val: string): void;
}

/**
 * 定义emits
 */
const emits = defineEmits<EmitType>();

/**
 * 监听props变化
 */
watch(
  () => props.modelValue,
  (newVal) => {
    valueHtml.value = newVal;
  },
);

/**
 * 定义editor实例
 */
const editorRef = shallowRef<IDomEditor | null>(null);

/**
 * 定义响应式数据
 */
const valueHtml = ref<string>('');
const mode = ref<string>('default');

/**
 * 工具类配置项
 */
const toolbarConfig = {};

/**
 * 编辑器主体配置项
 */
const editorConfig: Partial<IEditorConfig> = {
  placeholder: '',
  MENU_CONF: {
    uploadImage: {
      base64LimitSize: 10000000,
      server: '',
      metaWithUrl: false,
      onSuccess(file: any, res: any) {},
      onFailed(file: any, res: any) {},
      onError(file: any, res: any) {},
      async customUpload(file: File, insertFn: WangEditorInsertImage) {
        const oss: AliyunOss = new AliyunOss();
        const res: any = await oss.uploadImage(file);
        insertFn(res, '', '');
      },
    },
    uploadVideo: {
      server: '',
      metaWithUrl: false,
      onSuccess(file: any, res: any) {},
      onFailed(file: any, res: any) {},
      onError(file: any, res: any) {},
      async customUpload(file: any, insertFn: WangEditorInsertVideo) {
        const oss: AliyunOss = new AliyunOss();
        const res: any = await oss.uploadVideo(file);
        insertFn(res);
      },
    },
  },
};

/**
 * 编辑器初始化
 * @param editor
 */
function onEditorCreated(editor: IDomEditor): void {
  editorRef.value = editor;
  valueHtml.value = props.modelValue;
}

/**
 * 监听编辑器变化
 */
function onChangeEditor(): void {
  emits('update:modelValue', valueHtml.value);
}
</script>
